<?php
/*
Plugin Name: 简数采集器
Version: 1.0.4
Description: 简数(keydatas.com)是一个通用、简单、智能、在线的网页数据采集器，功能强大，操作简单。支持定时采集、支持自动发布，定时发布；图片下载支持存储到阿里云OSS、七牛对象存储、腾讯云对象存储。
Plugin URL:http://www.keydatas.com/
ForEmlog: 5.3.1;6.0.0;pro 1
Author: 
Author URL: 
*/
	!defined('EMLOG_ROOT') && exit('access deined!');
	$_REQ = keydatas_mergeRequest();
	$keydatasArray = unserialize(Option::get('keydatas'));
	$DB = MySql::getInstance();
	$CACHE = Cache::getInstance();
	if (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on") {
		$http = "https://";
	} else {
		$http =  "http://";
	}
	$domain = $http.str_replace('\\', '/', $_SERVER['HTTP_HOST']);

	if (isset($_REQ["__kds_flag"])){	
		if ($_REQ["__kds_flag"] == "post") {//提交

			//密码校验
			$keydatas_password = $keydatasArray['keydatas_password'];
			if (empty($_REQ['kds_password']) || addslashes($_REQ['kds_password']) != $keydatas_password) {
				keydatas_failRsp(1403, "password error", "提交的发布密码错误");
			}	
			
			//检查标题		
			$title  = isset($_REQ['title']) ? addslashes($_REQ['title']) : '';//标题	
			if (empty($title)) {
				keydatas_failRsp(1404, "title is empty", "标题不能为空");
			}
			//检查内容		
			$content  = isset($_REQ['content']) ? addslashes($_REQ['content']) : '';
			if (empty($content)) {
				keydatas_failRsp(1404, "content is empty", "内容不能为空");
			}
	 
			$version = Option::EMLOG_VERSION;
					
			try{
				//标题唯一校验			
				$keydatas_title_unique = $keydatasArray['keydatas_title_unique'];
				if($keydatas_title_unique=='true'){
					$gid=isTitleUnique($title);		
					//只返回id
					if($gid){
						$docFinalUrl=$domain.'/'.'?post='.$gid;
						//
						keydatas_successRsp(array("url" =>$docFinalUrl));	
					}
				}
			
				//发布日期处理
				$date  = isset($_REQ['date']) ? addslashes($_REQ['date']) : time();
				if(empty($date)){
					$date=time();
				}	
				
				$excerpt  = isset($_REQ['excerpt']) ? addslashes($_REQ['excerpt']) : '';
				$alias  = isset($_REQ['alias']) ? addslashes($_REQ['alias']) : '';

				 $authorId = 1;
				 $author =addslashes($_REQ['author']);
				 if (!empty($author)) {
					$existUid = userIsExist($author);
					if (!empty($existUid)) {
						$authorId=$existUid;
					} else{
						$userId = createUser($author);
						if (!empty($userId)){
							$authorId = $userId;
						}
					}
				}	
				// 查找分类，如找不到，就新增分类
				 $sortId = -1;
				 $sort =addslashes($_REQ['sort']);
				 if (!empty($sort)) {
					$existSid = sortIsExist($sort);
					if (!empty($existSid)) {
						$sortId=$existSid;
					} else{
						$newSortID = createSort($sort);
						if (!empty($newSortID)){
							$sortId = $newSortID;
						}
					}
				}
	
			
			$type  = 'blog';
			$views  = isset($_REQ['views']) ? intval($_REQ['views']) : 0;
			//$views  = 0;
			$comnum  = isset($_REQ['comnum']) ? intval($_REQ['comnum']) : 0;

			$attnum  =  0;
			$top  = isset($_REQ['top']) ? addslashes($_REQ['top']) : 'n';
			$sortop  = isset($_REQ['sortop']) ? addslashes($_REQ['sortop']) : 'n';
			$hide  = isset($_REQ['hide']) ? addslashes($_REQ['hide']) : 'n';
			$checked  = isset($_REQ['checked']) ? addslashes($_REQ['checked']) : 'y';
			$allow_remark  = isset($_REQ['allow_remark']) ? addslashes($_REQ['allow_remark']) : 'y';
			$password  = isset($_REQ['password']) ? addslashes($_REQ['password']) : '';
			$template  = isset($_REQ['template']) ? addslashes($_REQ['template']) : '';
			

				
			//写入数据库
			 $sql = "insert into ".DB_PREFIX."blog (gid,title,date,content,excerpt,alias,author,sortid,type,views,comnum,attnum,top,sortop,hide,checked,allow_remark,password,template) values (NULL,'$title','$date','$content','$excerpt','$alias','$authorId','$sortId','$type','$views','$comnum','$attnum','$top','$sortop','$hide','$checked','$allow_remark','$password','$template')"; 
			try{
				$DB->query($sql);
				$gid = $DB->insert_id();
				$DB->query("commit;");
			}catch (Exception $e){
				$DB->query("rollback;");
				keydatas_failRsp(1500, "insert db error", "插入数据库异常:".$e->getMessage());
			}
			if(!$gid){
			   keydatas_failRsp(1501, "save error", "文章插入失败");
			}
			
			//对标签进行处理
			$tag = isset($_REQ['tag']) ? addslashes($_REQ['tag']) : '' ;
			if (!empty($tag)) {
				$tag = str_replace("，",",",$tag);//把中文逗号替换成英文逗号
				$tagArray = explode(',',$tag);

				if (is_array($tagArray)) {
					$tagArray = array_unique($tagArray);
					for ($c = 0; $c < count($tagArray); $c++) {
						$tid = tagIsExist($tagArray[$c]);
						if (!$tid) {
							//新建立标签
							if ($version=='5.3.1'){
								$tid = createTag($tagArray[$c],','.$gid.',');
							}else{
								$tid = createTag($tagArray[$c],$gid);
							}
						} else {
							//标签存在就更新gid字符串
							if ($version=='5.3.1'){
								$gidStr =   getTagGidstr($tid).$gid.',';
							}else{
								$gidStr =   getTagGidstr($tid).','.$gid;
							}
							
							$sql = "update ".DB_PREFIX."tag set gid='$gidStr' where tid='$tid'";
							$DB->query($sql);
						}
						//拼tid字符串
						if ($c == 0){
							$tidStr=$tid;
						} else {
							$tidStr=$tidStr.','.$tid;
						}
					}
					if ($version=='5.3.1'){ 
						//不做操作
						$do='nodoing';
					}else{
						//更新blog的tag字段
						$sql = "update ".DB_PREFIX."blog set tags='$tidStr' where gid='$gid'";
						$DB->query($sql);
					}
				}
			} 
			
			
				$docFinalUrl=$domain.'/'.'?post='.$gid;
				
				downloadImages($_REQ);
				
				if ($version=='5.3.1'){ 
					//$CACHE->updateCache(array('sta', 'tags', 'newlog', 'logsort', 'logtags'));
					$CACHE->updateCache(array('logsort', 'logtags'));
				}else{
					$CACHE->updateCache('logsort');
				}
					
				keydatas_successRsp(array("url" => $docFinalUrl));

			} catch (Exception $ex) {
			keydatas_failRsp(500,'save-error',$ex->getMessage());  
			}		
		}
	}

	//判断标题是否重复
	function isTitleUnique($title){
		$DB = MySql::getInstance();
		$sql = "SELECT gid FROM ".DB_PREFIX."blog where title='$title' LIMIT 1";
		$result = $DB->query($sql);
		while($row = $DB->fetch_array($result)){
			$gid = $row['gid'];
		}			
		return isset($gid)?$gid:false;
	}

    //创建用户
     function createUser($author){
        $DB = MySql::getInstance();
		$username = $author;
		//密码是888888
		$password = '$P$BIbpV32p70t1uz9hPumJiEhCZcoxnk/';
		$role = 'writer';
		$ischeck = 'n';
		$sql = "insert into ".DB_PREFIX."user (uid,username,password,role,ischeck) values (NULL,'$username','$password','$role','$ischeck');"; 
		$result = $DB->query($sql);	
		$insertUserId = $DB->insert_id();
		if ($insertUserId) {
		   return $insertUserId;
		}
		return false;
    }

    //判断用户名是否存在
     function userIsExist($author){
	$DB = MySql::getInstance();
	$sql = "SELECT uid FROM ".DB_PREFIX."user where username='$author' LIMIT 1";
	$result = $DB->query($sql);
	while($row = $DB->fetch_array($result)){
		$uid = $row['uid'];
	}			
	if ($uid) {
		return $uid;
	} else {
		//如找不到的话，使用uid再找找看
		$sql = "SELECT uid FROM ".DB_PREFIX."user where uid='$author' LIMIT 1";
		$result = $DB->query($sql);
		while($row = $DB->fetch_array($result)){
			$uid = $row['uid'];
		}
		if ($uid) {
			return $uid;
		} else {
			return false;
		}
		}
	} 

    //创建创建分类
     function createSort($sort){
		$DB = MySql::getInstance();
		$sortname = $sort;
		$sql = "insert into ".DB_PREFIX."sort (sid,sortname) values (NULL,'$sortname');"; 
		$result = $DB->query($sql);	
		$insertSortId = $DB->insert_id();
		if ($insertSortId) {
		   return $insertSortId;
		}
		return false;
	}

    //判断分类名称是否存在
     function sortIsExist($sort){
		$DB = MySql::getInstance();
		$sql = "SELECT sid FROM ".DB_PREFIX."sort where sortname='$sort' LIMIT 1";
		$result = $DB->query($sql);
		while($row = $DB->fetch_array($result)){
			$sid = $row['sid'];
		}
		if ($sid) {
			return $sid;
		} else {
			return false;
		}
	}
	
    //判断标签名称是否存在
     function tagIsExist($tag){
		$DB = MySql::getInstance();
		$sql = "SELECT ifnull(min(tid),0) tid FROM ".DB_PREFIX."tag where tagname='$tag'";
		$result = $DB->query($sql);
		while($row = $DB->fetch_array($result)){
			$tid = $row['tid'];
		}
		if ($tid>0) {
			return $tid;
		} else {
			return false;
		}
	}
	
    //根据tid,取得gid字符串
     function getTagGidstr($tid){
		$DB = MySql::getInstance();
		$sql = "SELECT gid FROM ".DB_PREFIX."tag where tid='$tid'";
		$result = $DB->query($sql);
		while($row = $DB->fetch_array($result)){
			$tagGidstr = $row['gid'];
		}
		if (!empty($tagGidstr)) {
			return $tagGidstr;
		} else {
			return false;
		}
	}
	
    //创建标签
    function createTag($tag,$gid){
		$DB = MySql::getInstance();
		$sql = "insert into ".DB_PREFIX."tag (tid,tagname,gid) values (NULL,'$tag','$gid');"; 
		$result = $DB->query($sql);	
		$insertTagId = $DB->insert_id();
		if ($insertTagId) {
			return $insertTagId;
		}
		return false;
	}
	
	 /**
     * 获取文件完整路径
     * @return string
     */
	function getFilePath(){
		$rootUrl=dirname(dirname(dirname(dirname(__FILE__))));
		return $rootUrl.'/content/uploadfile';
	}
	
    /**
     * 查找文件夹，如不存在就创建并授权
     * @return string
     */
	function createFolders($dir){ 
		return is_dir($dir) or (createFolders(dirname($dir)) and mkdir($dir, 0777)); 
	}	
	
	////
	 function  downloadImages($post){	
	  try{

		$downloadFlag = isset($post['__kds_download_imgs_flag']) ? $post['__kds_download_imgs_flag'] : '';
		if (!empty($downloadFlag) && $downloadFlag== "true") {
			$docImgsStr = isset($post['__kds_docImgs']) ? $post['__kds_docImgs'] : '';
			
			if (!empty($docImgsStr)) {
				$docImgs = explode(',',$docImgsStr);
				if (is_array($docImgs)) {
					$uploadDir = getFilePath();
					foreach ($docImgs as $imgUrl) {
						$urlItemArr = explode('/',$imgUrl);
						$itemLen=count($urlItemArr);
						if($itemLen>=3){
							//
							$fileRelaPath=$urlItemArr[$itemLen-3].'/'.$urlItemArr[$itemLen-2];
							$imgName=$urlItemArr[$itemLen-1];
							$finalPath=$uploadDir. '/'.$fileRelaPath;
							if (createFolders($finalPath)) {
								$file = $finalPath . '/' . $imgName;
								if(!file_exists($file)){
									$doc_image_data = file_get_contents($imgUrl);
									file_put_contents($file, $doc_image_data);
								}
							}
						}
					}
				}
			}				
		}
	 } catch (Exception $ex) {
		
	 }		
	}	
	
	function keydatas_mergeRequest() {
		if (isset($_GET['__kds_flag'])) {
			$_REQ  = array_merge($_GET, $_POST);
		} else {
			$_REQ  = $_POST;
		}
		return $_REQ ;
	}

	function keydatas_successRsp($data = "", $msg = "") {
		keydatas_rsp(1,0, $data, $msg);
	}
	function keydatas_failRsp($code = 0, $data = "", $msg = "") {
		keydatas_rsp(0,$code, $data, $msg);
	}
	function keydatas_rsp($result = 1,$code = 0, $data = "", $msg = "") {
		die(json_encode(array("rs" => $result, "code" => $code, "data" => $data, "msg" => urlencode($msg))));
	}
	
	function keydatas_menu() {
		echo '
	<div class="sidebarsubmenu" id="keydatas"><a href="./plugin.php?plugin=keydatas">简数采集器</a></div>
	';
	}
	
	addAction('adm_sidebar_ext', 'keydatas_menu');